from strategy.StrategyTemplate import StrategyTemplate
from utils.jsl_data_map import default_columns
# from database.lhjy import engine
from strategy import strategy_filter
# from utils.simple_utls import code_fix
import pandas as pd


class Dao3(StrategyTemplate):
    """
    道哥转债池3:
        大涨回落策略
    """
    def __init__(self):
        super(Dao3, self).__init__()
        self.strategy_name = "大涨回落策略"
        self.strategy_descrption = "大涨回落策略"

    def run(self):
        self.data = strategy_filter.filter_base(self.data)
        filter_list = []

        for code in self.data ['转债代码']:
            code_with_pre = code_fix(code)
            try:
                if code_with_pre is not None:
                    code_table = pd.read_sql_table(code_with_pre, con=engine)
                    MA = 45
                    latest_table = code_table.tail(MA)
                    count = latest_table['turnover_rt'][latest_table['turnover_rt'].astype('float') > 100].count()
                    self.data.loc[self.data['转债代码'] == code, '均价'] = code_table['close'].rolling(MA).mean().iloc[-1]
                    if count > 1:
                        filter_list.append(code_with_pre[2:])
                    # avg_trunover_rt = (temp['turnover_rt'].astype('float').mean())
                    # pd.loc[pd["转债代码"] == code, '平均换手'] = avg_trunover_rt
            except ValueError as e:
                pass
        self.data = self.data[self.data['转债代码'].isin(filter_list)]
        self.data = self.data[self.data['现价'] < self.data['均价'] * 0.9]
        # 获得默认列
        self.data = self.data[default_columns]
        # 清掉原来的索引
        self.data.reset_index(inplace=True, drop=True)

if __name__ == '__main__':
    ins = Dao3()
    ins.topN = 20
    ins.test()